package utils

// 在文件顶部添加以下导入：
import (
	"fmt"
	"strconv"
	"sync"
	"time"
)

// 在文件底部添加雪花算法实现：
const (
	epoch        int64 = 1672531200000 // 2023-01-01 00:00:00 UTC 作为起始时间戳
	workerIDBits uint8 = 10            // 工作节点ID位数
	sequenceBits uint8 = 12            // 序列号位数
	maxWorkerID  int64 = -1 ^ (-1 << workerIDBits)
	maxSequence  int64 = -1 ^ (-1 << sequenceBits)
	timeShift    uint8 = workerIDBits + sequenceBits
	workerShift  uint8 = sequenceBits
)

type Snowflake struct {
	mu       sync.Mutex
	lastTime int64
	workerID int64
	sequence int64
}

// NewSnowflake 创建雪花算法实例
func NewSnowflake(workerID int64) (*Snowflake, error) {
	if workerID < 0 || workerID > maxWorkerID {
		return nil, fmt.Errorf("worker ID must be between 0 and %d", maxWorkerID)
	}
	return &Snowflake{
		workerID: workerID,
	}, nil
}

// Generate 生成唯一ID
func (s *Snowflake) Generate() int64 {
	s.mu.Lock()
	defer s.mu.Unlock()

	now := time.Now().UnixMilli()
	if now < s.lastTime {
		panic(fmt.Sprintf("clock moved backwards. Refusing to generate id for %d milliseconds", s.lastTime-now))
	}

	if now == s.lastTime {
		s.sequence = (s.sequence + 1) & maxSequence
		if s.sequence == 0 {
			for now <= s.lastTime {
				now = time.Now().UnixMilli()
			}
		}
	} else {
		s.sequence = 0
	}

	s.lastTime = now

	return ((now - epoch) << timeShift) |
		(s.workerID << workerShift) |
		s.sequence
}

func QuickGenerateID() string {
	snowflake, _ := NewSnowflake(1)
	return strconv.FormatInt(snowflake.Generate(), 10)
}
